<?php

/**
 * 自动生成 MerWxMaterialService
 * 
 * Apps/Common/Service/MerWxMaterialService.class.php
 * admin @ 2015-06-18
 */

namespace Common\Service;

class MerWxMaterialService {

  private static $instance;

  public static function instance() {
    if (self::$instance == null) {
      $instance = new MerWxMaterialService();
    }

    return $instance;
  }

  function get_default_row() {
    return array(
      'pid' => '0',
      'title' => '',
      'pic_url' => '',
      'author' => '',
      'digest' => '',
      'show_cover_pic' => '1',
      'content' => '',
      'url' => '',
      'count' => '1',
    );
  }

  function get_by_id($id) {
    $MerWxMaterial = M('MerWxMaterial');
    $data = $MerWxMaterial->find($id);
    return $data ? $data : array();
  }

  function get_by_cond($config) {
    $default = array(
      'page' => 1,
      'page_size' => 6,
      'status' => '',
      'count' => FALSE,
      'order' => 'DESC',
      'sort' => 'id',
    );

    $config = extend($config, $default);

    $MerWxMaterial = M('MerWxMaterial');

    $where = array();

    if (!empty($config['status'])) {
      $where['status'] = $config['status'];
    }

    if ($config['count']) {
      return $MerWxMaterial->where($where)->count();
    } else {
      $order = $config['sort'] . ' ' . $config['order'];
      $limit = ($config['page'] - 1 ) * $config['page_size'] . ' , ' . $config['page_size'];
      $data = $MerWxMaterial
          ->where($where)
          ->limit($limit)->order($order)->select();
      //echo $MerWxMaterial->_sql();
      return $data ? $data : array();
    }
  }

  function create($data) {
    $MerWxMaterial = M('MerWxMaterial');
    $ret = $MerWxMaterial->add($data);
    if ($ret) {
      return ajax_arr('添加成功', TRUE, array(
        'id' => $ret
      ));
    } else {
      return ajax_arr('添加失败', FALSE);
    }
  }

  function update($id, $data) {
    $MerWxMaterial = M('MerWxMaterial');

    $ret = $MerWxMaterial->where("id = %d", $id)->save($data);
    if ($ret) {
      return ajax_arr('编辑成功', TRUE);
    } else {
      return ajax_arr('编辑失败', FALSE);
    }
  }

  function delete($ids) {
    $MerWxMaterial = M('MerWxMaterial');
    $ret = $MerWxMaterial->delete($ids);
    if ($ret == 0) {
      return ajax_arr('未删除任何数据', FALSE);
    } else if (!$ret) {
      return ajax_arr('删除失败', FALSE);
    } else {
      return ajax_arr('删除' . $ret . '行数据', TRUE);
    }
  }

}
